/*
Filename:    address.h
Author:      Erik Öjebo
Date:        2008-11-19
Description: Represents the address of a host (client or server). Can be
             a specific address to connect to or a wild card address to accept
             connections from.
             Wraps the structs sockaddr_in and hostent, as well as a few
             associated functions.
*/

#ifndef _ADDRESS_H_
#define _ADDRESS_H_

#include <string>
#include <vector>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>

class Address
{
public:
    // Default constructor
    Address() {};

    // Creates an address with a specific port and a wild card IP (INADDR_ANY),
    // used for accepting incoming connections.
    Address(int portNumber);

    // Creates an address with a specific port and a specific ip, used for
    // connecting to a server.
    Address(const char* const address, int portNumber);

    // Creates an address from the given sockaddr_in structure
    Address(struct sockaddr_in const * const address);

    // Returns the address in dotted decimal form, i.e. 127.0.0.1
    const char* const getDottedDecimalRepresentation() const;

    // Returns the name of the host with the current address, i.e. localhost
    const char* const getHostName() const;

    // Returns a pointer to the sockaddr struct representation of the address.
    struct sockaddr const * const getSocketAddress() const;

    // Returns the size of the sockaddr struct returned by getSocketAddress().
    size_t getSocketAddressSize() const;

    // Returns the port number:
    int getPortNumber() const;

    // Retreives the IP addresses of all available network interfaces, and
    // creates an Address instance for each IP, with the port number given
    // by the caller. The instances are then added to the specified vector.
    static void getAllAvailable(
            std::vector<Address>& addresses, int portNumber);

private:
    // Initializes the host name and IP address buffers.
    void initializeBuffers();

    // Fills the given ifconf structure with information about the available
    // network interfaces.
    static void getInterfaceInformation(struct ifconf *ifconf);

    struct sockaddr_in socketAddress;
    char addressBuffer[INET_ADDRSTRLEN], hostnameBuffer[NI_MAXHOST];
};

#endif
